package com.why.whypaydemo.service;

import com.why.whypaydemo.confing.WeChatConfig;
import com.why.whypaydemo.util.CommonUtils;
import com.why.whypaydemo.util.HttpUtils;
import com.why.whypaydemo.util.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Service
public class WexinPCServiceImpl {

    @Resource
    private WeChatConfig weChatConfig;

    /**
     * 统一下单方法
     * @return
     */
    public String unifiedOrder() throws Exception {

        //int i = 1/0;   //模拟异常
        //生成签名
        SortedMap<String,String> params = new TreeMap<>();
        params.put("appid",weChatConfig.getAppId());
        params.put("mch_id", weChatConfig.getMchId());
        params.put("nonce_str", CommonUtils.generateUUID());
        params.put("body","你好");
        params.put("out_trade_no","1111");
        params.put("total_fee","1");
        params.put("spbill_create_ip","127.0.0.1");
//        params.put("openid",weChatConfig.getOpenAppid());
        params.put("sub_mch_id", weChatConfig.sub_mch_id);
        params.put("notify_url",weChatConfig.getPayCallbackUrl());
        params.put("trade_type","NATIVE");
//        params.put("trade_type","JSAPI");


        //sign签名
        String sign = WXPayUtil.createSign(params, weChatConfig.getKey());
        params.put("sign",sign);

        //map转xml
        String payXml = WXPayUtil.mapToXml(params);

        System.out.println(payXml);
        //统一下单
        String orderStr = HttpUtils.doPost(WeChatConfig.getUnifiedOrderUrl(),payXml,4000);
        if(null == orderStr) {
            return null;
        }

        Map<String, String> unifiedOrderMap =  WXPayUtil.xmlToMap(orderStr);
        System.out.println(unifiedOrderMap.toString());
        if(unifiedOrderMap != null) {
            return unifiedOrderMap.get("code_url");
        }

        return null;
    }

}
